import { createStore, applyMiddleware, compose, combineReducers } from 'redux';
import { reduxReactRouter } from 'redux-router';

import DevTools from '../containers/DevTools';
import { persistState } from 'redux-devtools';

import * as reducers from '../reducers';

import routes from '../../routes/route';
import createHistory from '../../routes/history';

import { logger } from '../middlewares/logger';
import { dataAPICallerMiddleware } from '../middlewares/dataAPICallerMiddleware';
import { conditionAPICallerMiddleware } from '../middlewares/conditionAPICallerMiddleware';

// function getDebugSessionKey() {
// 	// You can write custom logic here!
// 	// By default we try to read the key from ?debug_session=<key> in the address bar
// 	const matches = window.location.href.match(/[?&]debug_session=([^&]+)\b/);
// 	return (matches && matches.length > 0)? matches[1] : null;
// }

let finalCreateStore;
if (__DEV__ && __DEVTOOLS__) {
	finalCreateStore = compose(
		applyMiddleware(logger, dataAPICallerMiddleware, conditionAPICallerMiddleware),
		reduxReactRouter({routes, createHistory}),
		// Provides support for DevTools:
		DevTools.instrument()
		// Lets you write ?debug_session=<name> in address bar to persist debug sessions
		// ,persistState(getDebugSessionKey())
	)(createStore);
} else {
	finalCreateStore = compose(
		applyMiddleware(logger, dataAPICallerMiddleware, conditionAPICallerMiddleware),
		reduxReactRouter({routes, createHistory})
	)(createStore);
}

let rootReducer = combineReducers(reducers);

export default function configureStore(initialState) {
	return finalCreateStore(rootReducer, initialState)
}